import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { RedisService } from '../redis/redis.service';
import { LoggerService } from '@/common/logger/logger.service';
import { SendEmailDto } from './dto/send-email.dto';
import { customAlphabet } from 'nanoid'
import { RedisKeyEnum } from '../enums/redis-key.enum';
import { handleError } from '@/utils/handle.error';
import { ISendMailOptions, MailerService } from '@nestjs-modules/mailer';
import { formatTime } from '@/utils/date';

@Injectable()
export class EmailService {
  constructor(
    private readonly redisService: RedisService,
    private readonly logger: LoggerService,
    private readonly mailerService: MailerService
  ) {
    this.logger.setContext(EmailService.name);
  }

  async sendMail(info: SendEmailDto) {
    try {

      this.logger.log(`${this.sendMail.name} was called`);
      const key = RedisKeyEnum.LoginKey + info.email
      const redRes = await this.redisService.get(key)
      console.log('打印***redRes', redRes)
      if (redRes) {
        throw new HttpException('验证码未过期', HttpStatus.OK)
      }
      const code = this.genEmailCode()
      console.log('打印***code', code)
      this.redisService.setex(
        key,
        60 * 3,
        code,
      );
      const sendMailOptions: ISendMailOptions = {
        to: info.email,
        subject: '登录验证码',
        //这里写你的模板名称，如果你的模板名称的单名如 validate.ejs ,直接写validate即可 系统会自动追加模板的后缀名,如果是多个，那就最好写全。
        template: 'code.ejs',
        context: {
          code,
          date: formatTime(),
          sign: '系统邮件,回复无效。'
        }
      }
      await this.mailerService.sendMail(sendMailOptions)

      return `发送成功`
    } catch (error) {
      handleError(this.logger, error, {
        common: '发送失败'
      })
    }
  }

  /** 获取短信验证码 */
  genEmailCode() {
    const nanoid = customAlphabet('1234567890', 6)
    return nanoid()
  }


}
